const express = require('express')
const router = express.Router()
const db = require('../config/db')

// 获取所有字典数据
router.get('/list', async (req, res) => {
  try {
    const [rows] = await db.query(
      'SELECT id, dict_key, dict_value, description, created_at, updated_at FROM dictionary ORDER BY created_at DESC'
    )

    // 将数据库结果转换为前端需要的格式
    // dict_value 存储为 TEXT 类型的 JSON 字符串，需要手动解析
    const dictionaries = rows.map((row) => {
      let parsedValue
      try {
        parsedValue = JSON.parse(row.dict_value)
      } catch (e) {
        // 如果解析失败，返回原始字符串
        parsedValue = row.dict_value
      }
      return {
        id: row.id,
        key: row.dict_key,
        value: parsedValue,
        description: row.description,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
      }
    })

    // 如果希望返回为 key-value 对象格式（便于前端使用）
    const dictMap = {}
    rows.forEach((row) => {
      try {
        dictMap[row.dict_key] = JSON.parse(row.dict_value)
      } catch (e) {
        dictMap[row.dict_key] = row.dict_value
      }
    })

    res.json({
      data: {
        list: dictionaries,
        map: dictMap, // 额外的 map 格式，便于前端直接通过 key 获取 value
      },
      message: '获取成功',
      code: 200,
    })
  } catch (error) {
    console.error('获取字典数据失败:', error)
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 根据 key 获取单个字典数据
router.get('/:key', async (req, res) => {
  try {
    const { key } = req.params
    const [rows] = await db.query(
      'SELECT id, dict_key, dict_value, description, created_at, updated_at FROM dictionary WHERE dict_key = ?',
      [key]
    )

    if (rows.length === 0) {
      return res.status(404).json({
        data: null,
        message: '字典不存在',
        code: 404,
      })
    }

    const row = rows[0]
    let parsedValue
    try {
      parsedValue = JSON.parse(row.dict_value)
    } catch (e) {
      // 如果解析失败，返回原始字符串
      parsedValue = row.dict_value
    }

    res.json({
      data: {
        id: row.id,
        key: row.dict_key,
        value: parsedValue,
        description: row.description,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
      },
      message: '获取成功',
      code: 200,
    })
  } catch (error) {
    console.error('获取字典数据失败:', error)
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 根据 key 修改字典值
router.post('/update/:key', async (req, res) => {
  try {
    const { key } = req.params
    const { value } = req.body

    // 更新字典值
    const stringValue =
      typeof value === 'object' ? JSON.stringify(value) : String(value)
    const [result] = await db.query(
      'UPDATE dictionary SET dict_value = ?, updated_at = CURRENT_TIMESTAMP WHERE dict_key = ?',
      [stringValue, key]
    )

    if (result.affectedRows === 0) {
      return res.status(404).json({
        data: null,
        message: '字典不存在',
        code: 404,
      })
    }

    res.json({
      data: value,
      message: '更新成功',
      code: 200,
    })
  } catch (error) {
    console.error('更新字典值失败:', error)
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 新增字典项
router.post('/add', async (req, res) => {
  try {
    const { key, value, description } = req.body

    // 检查参数
    if (!key || value === undefined) {
      return res.status(400).json({
        data: null,
        message: '缺少必要参数：key 和 value',
        code: 400,
      })
    }

    // 检查 key 是否已存在
    const [existingRows] = await db.query(
      'SELECT id FROM dictionary WHERE dict_key = ?',
      [key]
    )

    if (existingRows.length > 0) {
      return res.status(400).json({
        data: null,
        message: '字典键已存在',
        code: 400,
      })
    }

    // 插入新字典项
    const stringValue =
      typeof value === 'object' ? JSON.stringify(value) : String(value)
    const [result] = await db.query(
      'INSERT INTO dictionary (dict_key, dict_value, description) VALUES (?, ?, ?)',
      [key, stringValue, description || '']
    )

    if (result.affectedRows === 1) {
      res.json({
        data: { key, value, description },
        message: '新增成功',
        code: 200,
      })
    } else {
      throw new Error('插入失败')
    }
  } catch (error) {
    console.error('新增字典项失败:', error)
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

module.exports = router
